package com.example.springbootapi.service.impl;

import com.example.springbootapi.entity.PayRecord;
import com.example.springbootapi.dto.PayRecordDTO;
import com.example.springbootapi.vo.PayRecordVO;
import com.example.springbootapi.mapper.PayRecordMapper;
import com.example.springbootapi.service.PayRecordService;
import com.example.springbootapi.common.PageResult;
import com.example.springbootapi.common.BusinessException;
import com.example.springbootapi.common.ErrorCode;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 支付记录表（存储支付流水，关联订单） 服务实现类
 * 
 * @author 开发者
 * @version 1.0.0
 * @since 2025-10-03
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class PayRecordServiceImpl extends ServiceImpl<PayRecordMapper, PayRecord> implements PayRecordService {

    @Override
    public PageResult<PayRecordVO> page(Integer pageNum, Integer pageSize, PayRecordDTO queryDTO) {
        // 构建查询条件
        LambdaQueryWrapper<PayRecord> queryWrapper = new LambdaQueryWrapper<>();
        
        // 动态查询条件构建
        if (queryDTO != null) {
            // 关联订单ID（外键：order_main.id）查询条件
            if (StringUtils.hasText(queryDTO.getOrderId())) {
                queryWrapper.eq(PayRecord::getOrderId, queryDTO.getOrderId());
            }
            // 订单编号（快照，与order_main.order_no一致）查询条件
            if (StringUtils.hasText(queryDTO.getOrderNo())) {
                queryWrapper.like(PayRecord::getOrderNo, queryDTO.getOrderNo());
            }
            // 第三方支付流水号（如微信支付transaction_id、支付宝trade_no）查询条件
            if (StringUtils.hasText(queryDTO.getPayNo())) {
                queryWrapper.like(PayRecord::getPayNo, queryDTO.getPayNo());
            }
            // 支付金额（与order_main.pay_amount一致，保留2位小数）查询条件
            if (queryDTO.getPayAmount() != null) {
                queryWrapper.eq(PayRecord::getPayAmount, queryDTO.getPayAmount());
            }
            // 支付方式（1&#x3D;微信支付，2&#x3D;支付宝，3&#x3D;银行卡）查询条件
            if (queryDTO.getPayType() != null) {
                queryWrapper.eq(PayRecord::getPayType, queryDTO.getPayType());
            }
            // 支付状态（1&#x3D;支付成功，2&#x3D;支付失败，3&#x3D;待确认）查询条件
            if (queryDTO.getPayStatus() != null) {
                queryWrapper.eq(PayRecord::getPayStatus, queryDTO.getPayStatus());
            }
            // 支付完成时间（未成功则为NULL）查询条件
            if (queryDTO.getPayTime() != null) {
                queryWrapper.eq(PayRecord::getPayTime, queryDTO.getPayTime());
            }
            // 支付失败原因（如&quot;余额不足&quot;、&quot;支付超时&quot;）查询条件
            if (StringUtils.hasText(queryDTO.getFailReason())) {
                queryWrapper.like(PayRecord::getFailReason, queryDTO.getFailReason());
            }
            // 逻辑删除（0&#x3D;未删除，1&#x3D;已删除）查询条件
            if (StringUtils.hasText(queryDTO.getIsDeleted())) {
                queryWrapper.eq(PayRecord::getIsDeleted, queryDTO.getIsDeleted());
            }
            // 创建时间（发起支付时间）查询条件
            if (queryDTO.getCreateTime() != null) {
                queryWrapper.eq(PayRecord::getCreateTime, queryDTO.getCreateTime());
            }
            // 更新时间查询条件
            if (queryDTO.getUpdateTime() != null) {
                queryWrapper.eq(PayRecord::getUpdateTime, queryDTO.getUpdateTime());
            }
        }
        
        // 默认按创建时间倒序
        queryWrapper.orderByDesc(PayRecord::getCreateTime);
        
        // 分页查询
        IPage<PayRecord> page = new Page<>(pageNum, pageSize);
        IPage<PayRecord> result = this.page(page, queryWrapper);
        
        // 转换为VO
        List<PayRecordVO> voList = result.getRecords().stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());
        
        return PageResult.<PayRecordVO>builder()
                .records(voList)
                .total(result.getTotal())
                .current(result.getCurrent())
                .size(result.getSize())
                .pages(result.getPages())
                .build();
    }

    @Override
    public PayRecordVO getById(Long id) {
        PayRecord entity = this.getById(id);
        if (entity == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND, "支付记录表（存储支付流水，关联订单）不存在");
        }
        return convertToVO(entity);
    }

    @Override
    public PayRecordVO create(PayRecordDTO DTO) {
        // 参数验证
        validateDTO(DTO);
        
        // 转换为实体
        PayRecord entity = convertToEntity(DTO);
        entity.setCreateTime(LocalDateTime.now());
        entity.setUpdateTime(LocalDateTime.now());
        
        // 保存
        boolean success = this.save(entity);
        if (!success) {
            throw new BusinessException(ErrorCode.OPERATION_FAILED, "创建支付记录表（存储支付流水，关联订单）失败");
        }
        
        return convertToVO(entity);
    }

    @Override
    public PayRecordVO update(Long id, PayRecordDTO DTO) {
        // 检查记录是否存在
        PayRecord existingEntity = this.getById(id);
        if (existingEntity == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND, "支付记录表（存储支付流水，关联订单）不存在");
        }
        
        // 参数验证
        validateDTO(DTO);
        
        // 更新实体
        PayRecord entity = convertToEntity(DTO);
        entity.setId(id);
        entity.setUpdateTime(LocalDateTime.now());
        
        // 保存
        boolean success = this.updateById(entity);
        if (!success) {
            throw new BusinessException(ErrorCode.OPERATION_FAILED, "更新支付记录表（存储支付流水，关联订单）失败");
        }
        
        return convertToVO(entity);
    }

    @Override
    public void delete(Long id) {
        // 检查记录是否存在
        PayRecord entity = this.getById(id);
        if (entity == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND, "支付记录表（存储支付流水，关联订单）不存在");
        }
        
        // 删除
        boolean success = this.removeById(id);
        if (!success) {
            throw new BusinessException(ErrorCode.OPERATION_FAILED, "删除支付记录表（存储支付流水，关联订单）失败");
        }
    }

    @Override
    public void batchDelete(List<Long> ids) {
        if (ids == null || ids.isEmpty()) {
            throw new BusinessException(ErrorCode.INVALID_PARAMS, "删除ID列表不能为空");
        }
        
        // 批量删除
        boolean success = this.removeByIds(ids);
        if (!success) {
            throw new BusinessException(ErrorCode.OPERATION_FAILED, "批量删除支付记录表（存储支付流水，关联订单）失败");
        }
    }

    // 关联关系查询方法将在后续版本中支持

    /**
     * 实体转VO
     */
    private PayRecordVO convertToVO(PayRecord entity) {
        if (entity == null) {
            return null;
        }
        
        PayRecordVO vo = new PayRecordVO();
        BeanUtils.copyProperties(entity, vo);
        return vo;
    }

    /**
     * DTO转实体
     */
    private PayRecord convertToEntity(PayRecordDTO dto) {
        if (dto == null) {
            return null;
        }
        
        PayRecord entity = new PayRecord;
        BeanUtils.copyProperties(dto, entity);
        return entity;
    }

    /**
     * 验证DTO参数
     */
    private void validateDTO(PayRecordDTO dto) {
        if (dto == null) {
            throw new BusinessException(ErrorCode.INVALID_PARAMS, "支付记录表（存储支付流水，关联订单）信息不能为空");
        }
        
        // 必填字段验证
        if (!StringUtils.hasText(dto.getOrderId())) {
            throw new BusinessException(ErrorCode.INVALID_PARAMS, "关联订单ID（外键：order_main.id）不能为空");
        }
        if (!StringUtils.hasText(dto.getOrderNo())) {
            throw new BusinessException(ErrorCode.INVALID_PARAMS, "订单编号（快照，与order_main.order_no一致）不能为空");
        }
        if (dto.getPayAmount() == null) {
            throw new BusinessException(ErrorCode.INVALID_PARAMS, "支付金额（与order_main.pay_amount一致，保留2位小数）不能为空");
        }
        if (dto.getPayType() == null) {
            throw new BusinessException(ErrorCode.INVALID_PARAMS, "支付方式（1&#x3D;微信支付，2&#x3D;支付宝，3&#x3D;银行卡）不能为空");
        }
        if (dto.getPayStatus() == null) {
            throw new BusinessException(ErrorCode.INVALID_PARAMS, "支付状态（1&#x3D;支付成功，2&#x3D;支付失败，3&#x3D;待确认）不能为空");
        }
    }
}
